import React, { Component } from 'react'
import PropTypes from 'prop-types'
import store from '../stateFactory/Store'
import * as Actions from '../stateFactory/Actions'
// 容器式组件-用来与store交互
class CounterContainer extends Component {
  constructor (props) {
    super(props)
    this.state = this.getOwnState()
    this.onClickIncrementButton = this.onClickIncrementButton.bind(this)
    this.onClickDecrementButton = this.onClickDecrementButton.bind(this)
    this.onChange = this.onChange.bind(this)
  }
  getOwnState () {
    return {
      value: store.getState()[this.props.caption]
    }
  }
  onClickIncrementButton () {
    store.dispatch(Actions.increment(this.props.caption))
  }
  onClickDecrementButton () {
    store.dispatch(Actions.decrement(this.props.caption))
  }
  onChange () {
    this.setState(this.getOwnState())
  }
  // 保持组件内state与store中的一致
  componentDidMount () {
    store.subscribe(this.onChange)
  }
  componentWillUnmount () {
    store.unsubscribe(this.onChange)
  }
  render () {
    const {caption} = this.props
    return (
      <Counter 
        caption={caption}
        onClickIncrementButton={this.onClickIncrementButton}
        onClickDecrementButton={this.onClickDecrementButton}
        value={this.state.value}
      />
    )
  }
}
// 傻瓜式组件，只用来展示
class Counter extends Component {
  render () {
    const {caption, onClickIncrementButton, onClickDecrementButton, value} = this.props
    return (
      <div>
        <button onClick={onClickIncrementButton}>+</button>
        <button onClick={onClickDecrementButton}>-</button>
        <span>{caption} Count: {value}</span>
      </div>
    )
  }
}
CounterContainer.propTypes = {
  caption: PropTypes.string,
  initValue: PropTypes.number.isRequired
}
CounterContainer.defaultProps = {
  caption: 'default'
}
export default CounterContainer
